<template>
  <div class="app-container">
    <el-divider>
      <div class="my-divider">基础信息</div>
    </el-divider>

    <el-form ref="form" :model="form" :rules="rules" label-width="80px" size="small" label-position="left">
      <el-form-item label="检验单名称" prop="outQuaName">
        <el-input v-model="form.outQuaName" placeholder="请输入质检单名称"
                  class="my-input"
        />
      </el-form-item>
      <el-form-item label="发货日期" prop="outQuaDate">
        <el-date-picker clearable
                        v-model="form.outQuaDate"
                        type="date"
                        value-format="yyyy-MM-dd hh:mm:ss"
                        placeholder="请选择质检时间"
                        class="my-input"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="检验日期" prop="outQuaCheckDate">
        <el-date-picker clearable
                        v-model="form.outQuaCheckDate"
                        type="date"
                        value-format="yyyy-MM-dd hh:mm:ss"
                        placeholder="请选择质检时间"
                        class="my-input"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="检验人" prop="outQuaPeo">
        <MyPopoverBtn placeholder="请选择检验人" :content="form.outQuaPeoName" @click="() => qcPeoDialogVisible = true"
                      class="my-input"
        />
      </el-form-item>
      <el-form-item label="备注" prop="outQuaDesc" class="my-desc">
        <el-input v-model="form.outQuaDesc" type="textarea" placeholder="请输入内容" :autosize="{minRows: 3}"
        />
      </el-form-item>

      <el-divider>
        <div class="my-divider">物料信息</div>
      </el-divider>
      <el-form-item label="产品名称" prop="outQuaProduct">
        <MyPopoverBtn placeholder="请选择产品" :content="selectedProduct.pdName"
                      @click="() => productDialogTableVisible = true"
        />
      </el-form-item>
      <el-form-item label="产品编号">
        <el-input :value="selectedProduct.pdCode"
                  class="my-input" disabled
        />
      </el-form-item>
      <el-form-item label="规格型号">
        <el-input :value="selectedProduct.pdSpecType"
                  class="my-input" disabled
        />
      </el-form-item>
      <el-form-item label="产品类型">
        <el-input
          :value="selectedProduct.gbsGoodClass ? selectedProduct.gbsGoodClass.gcName : ''"
          class="my-input" disabled
        />
      </el-form-item>
      <el-form-item label="单位">
        <el-input
          :value="selectedProduct.gbsGoodUnit ? selectedProduct.gbsGoodUnit.guName : ''"
          class="my-input" disabled
        />
      </el-form-item>
      <el-form-item label="批次号" prop="outQuaBatch">
        <MyPopoverBtn placeholder="请选择批次" :content="form.outQuaBatch" @click="openBatchDialog" />
      </el-form-item>


      <el-divider>
        <div class="my-divider">检验项目</div>
      </el-divider>
      <div style="display: block;flex: 1">
        <div>
          <el-button type="primary" @click="handleToAddProject">添加</el-button>
          <el-button type="primary" plain @click="handleRemoveProject">
            移除
          </el-button>
        </div>
        <el-table :data="form.selectedProjectList ? form.selectedProjectList: []"
                  @selection-change="selectChangeProject"
        >
          <el-table-column type="selection" align="center" />
          <el-table-column label="序号" type="index" align="center" />
          <el-table-column label="质检项目编码" align="center" prop="qualityCode" />
          <el-table-column label="项目名称" align="center" prop="qualityProjectName" />
          <el-table-column label="检验标准" align="center" prop="qualityProjectStandard" />
          <el-table-column label="项目最大值" align="center" prop="qualityProjectMax" />
          <el-table-column label="项目最小值" align="center" prop="qualityProjectMin" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                v-hasPermi="['qc:project:query']"
                @click="lookDrawbackDialog(scope.$index)"
              >查看缺陷
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                v-hasPermi="['qc:project:edit']"
                @click="openDrawbackDialog(scope.$index)"
              >缺陷填报
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <el-divider>
        <div class="my-divider">检验结果</div>
      </el-divider>
      <el-form-item label="检测数量" prop="outQuaNum">
        <el-input-number v-model="form.outQuaNum"
                         class="my-input"
        />
      </el-form-item>
      <el-form-item label="合格数量" prop="outQuaGood">
        <el-input-number v-model="form.outQuaGood"
                         class="my-input"
        />
      </el-form-item>
      <el-form-item label="检测结果" prop="outQuaResult">
        <el-select
          v-model="form.outQuaResult"
          placeholder="请选择检验类型"
          class="my-input"
        >
          <el-option
            v-for="dict in getQualityYesNo"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <!--    提交按钮-->
    <MyConfirmBtnGroup :after-cancel-open-page="backPage" :ok-event="submitForm" />

    <!--    选择检验人 -->
    <el-dialog title="选择检验人" :visible.sync="qcPeoDialogVisible" width="50%" append-to-body>
      <RuoYiUserTree :selected-user.sync="preSelectedQcPeo" @close="closeQcPeoDialog" />
    </el-dialog>

    <!--    选择质检项目-->
    <el-dialog title="选择质检项目" :visible.sync="projectDialogVisible" width="50%" append-to-body>
      <el-form :model="projectQueryParams" ref="projectQueryForm" size="small" :inline="true" label-width="68px">
        <el-form-item label="质检编码" prop="qualityCode">
          <el-input
            v-model="projectQueryParams.qualityCode"
            placeholder="请输入质检项目编码"
            clearable
            @keyup.enter.native="projectHandleQuery"
          />
        </el-form-item>
        <el-form-item label="项目名称" prop="qualityProjectName">
          <el-input
            v-model="projectQueryParams.qualityProjectName"
            placeholder="请输入项目名称"
            clearable
            @keyup.enter.native="projectHandleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="projectHandleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="projectResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="projectLoading" :data="projectList"
                @selection-change="selectChangePreProject"
      >
        <el-table-column type="selection" align="center" />
        <el-table-column type="index" label="序号" align="center" />
        <el-table-column label="质检项目编码" align="center" prop="qualityCode" />
        <el-table-column label="项目名称" align="center" prop="qualityProjectName" />
        <el-table-column label="检验标准" align="center" prop="qualityProjectStandard" />
        <el-table-column label="项目最大值" align="center" prop="qualityProjectMax" />
        <el-table-column label="项目最小值" align="center" prop="qualityProjectMin" />
      </el-table>

      <pagination
        v-show="projectTotal>0"
        :total="projectTotal"
        :page.sync="projectQueryParams.pageNum"
        :limit.sync="projectQueryParams.pageSize"
        @pagination="projectGetList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="okProject">确 定</el-button>
        <el-button @click="cancelProject">取 消</el-button>
      </div>
    </el-dialog>

    <!--    选择缺陷-->
    <el-dialog title="选择缺陷" :visible.sync="drawbackDialogVisible" width="50%" append-to-body>
      <el-form :model="drawbackQueryParams" ref="drawbackQueryForm" size="small" :inline="true" label-width="68px">
        <el-form-item label="缺陷编号" prop="drawbackCode">
          <el-input
            v-model="drawbackQueryParams.drawbackCode"
            placeholder="请输入缺陷编号"
            clearable
            @keyup.enter.native="drawbackHandleQuery"
          />
        </el-form-item>
        <el-form-item label="缺陷名称" prop="drawbackName">
          <el-input
            v-model="drawbackQueryParams.drawbackName"
            placeholder="请输入缺陷名称"
            clearable
            @keyup.enter.native="drawbackHandleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="drawbackHandleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="drawbackResetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table ref="drawbackTable" v-loading="drawbackLoading" :data="drawbackList"
                @selection-change="handleSelectDrawbackChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="缺陷编号" align="center" prop="drawbackCode" />
        <el-table-column label="缺陷名称" align="center" prop="drawbackName" />
        <el-table-column label="缺陷类型编码" align="center" prop="qcDrawbackType.drawbackTypeName" />
        <el-table-column label="缺陷状态" align="center" prop="drawbackStatus">
          <template slot-scope="scope">
            <dict-tag :options="getStatus" :value="scope.row.drawbackStatus" />
          </template>
        </el-table-column>
        <el-table-column label="缺陷描述" align="center" prop="drawbackDetail" />
      </el-table>

      <pagination
        v-show="drawbackTotal>0"
        :total="drawbackTotal"
        :page.sync="drawbackQueryParams.pageNum"
        :limit.sync="drawbackQueryParams.pageSize"
        @pagination="drawbackGetList"
      />

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="okDrawback">确 定</el-button>
        <el-button @click="cancelDrawback">取 消</el-button>
      </div>
    </el-dialog>

    <!--    查看缺陷-->
    <el-dialog title="缺陷" :visible.sync="projectDrawbackDialogVisible" width="50%" append-to-body>
      <el-table ref="projectDrawbackTable" :data="projectDrawbackList">
        <el-table-column label="缺陷编号" align="center" prop="drawbackCode" />
        <el-table-column label="缺陷名称" align="center" prop="drawbackName" />
        <el-table-column label="缺陷类型编码" align="center" prop="qcDrawbackType.drawbackTypeName" />
        <el-table-column label="缺陷状态" align="center" prop="drawbackStatus">
          <template slot-scope="scope">
            <dict-tag :options="getStatus" :value="scope.row.drawbackStatus" />
          </template>
        </el-table-column>
        <el-table-column label="缺陷描述" align="center" prop="drawbackDetail" />
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDrawback">关 闭</el-button>
      </div>
    </el-dialog>

    <!--    选择产品-->
    <MyGoodDialog title="选择产品"
                  v-model="productDialogTableVisible"
                  :good.sync="selectedProduct"
                  :showTabs="false"
                  :single-mode="true"
                  show-content="product"
    />

    <!--    选择批次-->
    <el-dialog title="选择批次" :visible.sync="batchDialogVisible" width="50%" append-to-body>

      <el-table v-loading="batchLoading" :data="batchList" highlight-current-row
                @current-change="handleChangeCurrentBatch"
      >
        <el-table-column label="序号" align="center" width="100">
          <template slot-scope="scope">
            <div style="display: inline-block; margin-right: 20px">
              <MyRadio v-model="selectedBatch.storageBatch"
                       :label="scope.row.storageBatch"
                       radio-name="selectedBatch"
              />
            </div>
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="批次" width="100" align="center" prop="storageBatch" show-overflow-tooltip />
        <el-table-column label="产品编码" width="150" align="center" prop="pdCode" show-overflow-tooltip />
        <el-table-column label="产品名称" align="center" width="120" prop="pdName" show-overflow-tooltip />
        <el-table-column label="BOM" align="center" prop="pdBomCode" show-overflow-tooltip />
        <!--        <el-table-column label="BOM版本" align="center" prop="pdBomVersion" show-overflow-tooltip />-->
        <el-table-column label="当前库存" align="center" prop="storageNum" show-overflow-tooltip />
      </el-table>

      <pagination
        v-show="batchTotal>0"
        :total="batchTotal"
        :page.sync="batchQueryParams.pageNum"
        :limit.sync="batchQueryParams.pageSize"
        @pagination="getStorageList"
      />

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="okBatch">确 定</el-button>
        <el-button @click="cancelBatch">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import MyPopoverBtn from '@/components/MyPopoverBtn/index.vue'
import MyConfirmBtnGroup from '@/components/MyConfirmBtnGroup/index.vue'
import { addOutgoingQuality, getOutgoingQuality, updateOutgoingQuality } from '@/api/yyj/qc/outgoingQuality'
import { listDrawback } from '@/api/yyj/qc/drawback'
import MyGoodDialog from '@/components/MyGoodDialog/index.vue'
import { listProject } from '@/api/yyj/qc/project'
import RuoYiUserTree from '@/components/RuoYiUserTree/index.vue'
import { listProduct } from '@/api/yyj/wm/info/goods'
import MyRadio from '@/components/MyRadio/index.vue'

export default {
  name: 'outgoingQualityChange',
  components: { MyRadio, RuoYiUserTree, MyGoodDialog, MyConfirmBtnGroup, MyPopoverBtn },
  dicts: ['qc_quality_type', 'yyj_common_status', 'qc_quality_yes_no'],
  data() {
    return {
      backPage: '/qc/outgoingQuality',
      productDialogTableVisible: false,
      qcPeoDialogVisible: false,
      projectDialogVisible: false,
      drawbackDialogVisible: false,
      batchDialogVisible: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        outQuaName: [
          { required: true, message: '检验单名称不能为空', trigger: 'blur' }
        ],
        outQuaDate: [
          { required: true, message: '发货日期不能为空', trigger: 'blur' }
        ],
        outQuaCheckDate: [
          { required: true, message: '检验日期不能为空', trigger: 'blur' }
        ],
        outQuaPeo: [
          { required: true, message: '检验人不能为空', trigger: 'blur' }
        ],
        outQuaNum: [
          { required: true, message: '质检数量不能为空', trigger: 'blur' }
        ],
        outQuaGood: [
          { required: true, message: '合格数量不能为空', trigger: 'blur' }
        ],
        outQuaResult: [
          { required: true, message: '质检结果不合格不能为空', trigger: 'change' }
        ],
        outQuaProduct: [
          { required: true, message: '质检产品不能为空', trigger: 'blur' }
        ],
        outQuaBatch: [
          { required: true, message: '质检批次号不能为空', trigger: 'blur' }
        ]
      },
      // 检验人list
      qcPeoList: [],
      // 预选检验人
      preSelectedQcPeo: {},
      // 质检项目加载
      projectLoading: false,
      preSelectedProjectList: [],
      // 准备移除的项目
      preRemoveProjectList: [],
      // dialog - project
      projectList: [],
      // 总条数
      projectTotal: 0,
      // 查询参数
      projectQueryParams: {
        pageNum: 1,
        pageSize: 10,
        qualityCode: null,
        qualityProjectName: null,
        qualityProjectStandard: null,
        qualityProjectMax: null,
        qualityProjectMin: null,
        qualityProjectDesc: null
      },
      // 查询参数
      drawbackQueryParams: {
        pageNum: 1,
        pageSize: 10,
        drawbackCode: null,
        drawbackTypeCode: null,
        drawbackTypeName: null,
        drawbackName: null,
        drawbackStatus: null,
        drawbackDetail: null,
        drawbackDesc: null
      },
      drawbackLoading: false,
      drawbackTotal: 0,
      drawbackList: [],
      preSelectedDrawbackList: [],
      currentDrawbackIndex: -1,
      projectDrawbackDialogVisible: false,
      projectDrawbackList: [],
      // 选择的产品
      selectedProduct: {},
      // 批次总数
      batchTotal: 0,
      // 批次加载
      batchLoading: true,
      // 批次请求参数
      batchQueryParams: {
        pageNum: 1,
        pageSize: 10,
        pdCode: ''
      },
      // 批次信息
      batchList: [],
      // 选择的批次
      selectedBatch: {}
    }
  },
  created() {
    const outQuaCode = this.$route.params.outQuaCode
    if (outQuaCode) {
      Promise.all([
        this.projectGetList(),
        this.drawbackGetList(),
        this.getDetail(outQuaCode)
      ])
    } else {
      Promise.all([
        this.projectGetList(),
        this.drawbackGetList()
      ])
    }
  },
  watch: {
    selectedProduct: {
      handler(nVal) {
        this.form.selectedGood = nVal
        this.form.outQuaProduct = this.form.selectedGood.pdCode
      },
      immediate: true
    }
  },
  computed: {
    getQualityType() {
      return this.dict.type.qc_quality_type
    },
    getStatus() {
      return this.dict.type.yyj_common_status
    },
    getQualityYesNo() {
      return this.dict.type.qc_quality_yes_no
    }
  },
  methods: {
    // 切换当前选择的batch
    handleChangeCurrentBatch(selection) {
      this.selectedBatch = selection
    },
    // 确认批次
    okBatch() {

    },
    // 取消批次
    cancelBatch() {
      this.batchDialogVisible = false
    },
    // 打开批次弹窗
    openBatchDialog() {
      if (!this.form.outQuaProduct) {
        this.$modal.msgError('请先选择产品')
        return
      }
      // 发送请求
      this.getStorageList()
      this.batchDialogVisible = true
    },
    // 获取库存信息
    async getStorageList() {
      this.batchLoading = true
      this.batchQueryParams.pdCode = this.form.outQuaProduct
      const res = await listProduct(this.batchQueryParams)
      console.log('res ', res)
      this.batchList = res.rows
      this.batchTotal = res.total
      this.batchLoading = false
    },
    // 获取详情
    async getDetail(outQuaCode) {
      const res = await getOutgoingQuality(outQuaCode)
      console.log('before res ', res)
      this.form = res.data
      this.selectedProduct = res.data.gbsGood
      this.form.selectedQcPeo = res.selectedQcPeo
      this.form.selectedProjectList = res.selectedProjectList
    },
    // 打开质检人弹窗
    closeQcPeoDialog() {
      this.form.selectedQcPeo = { ...this.preSelectedQcPeo }
      this.form.outQuaPeo = this.form.selectedQcPeo.userId
      this.form.outQuaPeoName = this.form.selectedQcPeo.userName
      this.qcPeoDialogVisible = false
    },
    lookDrawbackDialog(index) {
      this.projectDrawbackList = this.form.selectedProjectList[index].drawbackList
      this.projectDrawbackDialogVisible = true
    },
    /** 查询质检项目列表 */
    async projectGetList() {
      this.projectLoading = true
      const res = await listProject(this.projectQueryParams)
      this.projectList = res.rows
      this.projectTotal = res.total
      this.projectLoading = false
    },
    closeDrawback() {
      this.projectDrawbackList = []
      this.projectDrawbackDialogVisible = false
    },
    // 打开drawback-dialog
    openDrawbackDialog(index) {
      this.currentDrawbackIndex = index
      this.drawbackDialogVisible = true
    },
    okDrawback() {
      this.form.selectedProjectList[this.currentDrawbackIndex].drawbackList = this.preSelectedDrawbackList
      console.log(this.form.selectedProjectList)
      this.cancelDrawback()
    },
    cancelDrawback() {
      this.currentDrawbackIndex = -1
      this.drawbackDialogVisible = false
    },
    // 预选择drawback
    handleSelectDrawbackChange(selection) {
      this.preSelectedDrawbackList = selection
    },
    /** 搜索按钮操作 */
    drawbackHandleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    drawbackResetQuery() {
      this.resetForm('drawbackQueryForm')
      this.drawbackHandleQuery()
    },
    /** 查询缺陷列表 */
    async drawbackGetList() {
      this.drawbackLoading = true
      const res = await listDrawback(this.drawbackQueryParams)
      this.drawbackList = res.rows
      this.drawbackTotal = res.total
      this.drawbackLoading = false
    },
    // 预选择project
    selectChangePreProject(selection) {
      this.preSelectedProjectList = selection
    },
    // 确定项目
    okProject() {
      this.form.selectedProjectList = this.preSelectedProjectList
      this.cancelProject()
    },
    // 取消项目
    cancelProject() {
      this.projectDialogVisible = false
    },
    /** 搜索按钮操作 */
    projectHandleQuery() {
      this.projectQueryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    projectResetQuery() {
      this.resetForm('projectQueryForm')
      this.projectHandleQuery()
    },
    // 选择项目
    selectChangeProject(selection) {
      this.preRemoveProjectList = selection
    },
    // 去添加项目
    handleToAddProject() {
      this.projectDialogVisible = true
    },
    // 移除已选择的项目
    handleRemoveProject(index) {
      this.form.selectedProjectList.splice(index, 1)
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(async valid => {
        if (valid) {
          console.log('this.form ', this.form)
          // return
          this.$modal.loading('正在提交...')
          if (this.form.outQuaCode != null) {
            await updateOutgoingQuality(this.form)
            this.$modal.msgSuccess('修改成功')
          } else {
            await addOutgoingQuality(this.form)
            this.$modal.msgSuccess('新增成功')
          }
          this.afterSubmit()
        }
      })
    },
    afterSubmit() {
      this.$tab.closeOpenPage()
      this.reset()
      this.$tab.refreshPage({
        path: this.backPage
      })
      this.$modal.closeLoading()
    },
    // 表单重置
    reset() {
      this.form = {}
      this.resetForm('form')
    }
  }
}
</script>

<style scoped lang="scss">
@import '@/assets/styles/yyj/change';
</style>
